package com.happy.shiro.config;

import com.happy.shiro.config.shiro.ShiroRedisCacheManger;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {

    @Bean
    public CacheManager shiroCacheManager(org.springframework.cache.CacheManager cacheManager) {
        return new ShiroRedisCacheManger(cacheManager);
    }

    @Bean
    public SessionDAO sessionDAO(CacheManager shiroCacheManager) {
        EnterpriseCacheSessionDAO enterpriseCacheSessionDAO = new EnterpriseCacheSessionDAO();
        enterpriseCacheSessionDAO.setCacheManager(shiroCacheManager);
        return enterpriseCacheSessionDAO;
    }

    @Bean
    public Realm customRealm() {
        SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();
        simpleAccountRealm.addRole("admin");
        simpleAccountRealm.addRole("normal");
        simpleAccountRealm.addAccount("cxl", "123", "admin");
        simpleAccountRealm.addAccount("xgy", "123", "normal");
        simpleAccountRealm.setAuthenticationCachingEnabled(true);
        simpleAccountRealm.setAuthorizationCachingEnabled(true);
        return simpleAccountRealm;
    }

    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
        chainDefinition.addPathDefinition("/favicon.ico", "anon");
        chainDefinition.addPathDefinition("/login.html", "anon");
        chainDefinition.addPathDefinition("/auth/login", "anon");
        chainDefinition.addPathDefinition("/auth/logout", "logout");
        chainDefinition.addPathDefinition("/**", "authc");
        return chainDefinition;
    }
}